<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <title>Lesson {{ lesson.id }} {{ lesson.title }}</title>

    <!-- Bootstrap core CSS -->
    <link href="{{ url_for('static', filename='vendor/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
    <link rel="stylesheet" href="{{ url_for('static', filename='thirdassets/css/fontawesome.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='thirdassets/css/templatemo-style.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='thirdassets/css/owl.css') }}">
    <!-- 修改CSS部分 -->
    <style>
        /* 句子容器样式 */
       .sentence-container {
            position: relative;
            margin: 10px 0;
            padding: 10px;
            border-radius: 6px;
            line-height: 1.8;
            word-wrap: break-word;
        }

        /* 进度文字样式 */
       .progress-text {
            color: #2196f3;
            transition: color 0.3s ease;
        }

        /* 对话样式 */
       .dialogue-block {
            border-left: 3px solid #e0f7fa;
            padding-left: 15px;
        }

        /* 悬浮效果 */
       .sentence-container:hover {
            background: rgba(33, 150, 243, 0.05);
            transform: translateX(5px);
            transition: all 0.3s ease;
        }
    </style>
    <script>
        // 检测浏览器是否支持语音合成
        var speechSupport = ('speechSynthesis' in window);
    </script>
</head>

<body class="is-preload">

<!-- Wrapper -->
<div id="wrapper">

    <!-- Main -->
    <div id="main">
        <div class="inner">

            <!-- Header -->
            <header id="header">
                <div class="logo">
                    <a>Lesson {{ lesson.id }}</a>
                </div>
            </header>

            <!-- Banner -->
            <section class="main-banner">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="banner-content">
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="banner-caption">
                                            <h4>{{ lesson.title }}</h4>
                                            <h5>{{ lesson.pinyin }}</h5>
                                            <span>{{ lesson.description }}</span>
                                            <p>
                                                {{ lesson.banner_content }}</p>
                                            <div class="primary-button">
                                                <button onclick="window.history.back()">Return</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
<script>
                let currentAudio;
                let currentSentence;
                let progressInterval;

                // 语音合成函数（纯文字变色版）
                function speakText(text, sentenceElement) {
                    if (!text) return;

                    // 停止上次播放并重置样式
                    if (currentAudio) {
                        currentAudio.pause();
                        clearInterval(progressInterval);
                        resetSentenceColor(sentenceElement);
                    }

                    currentSentence = sentenceElement;
                    const originalText = sentenceElement.textContent;
                    const wordArray = originalText.split(''); // 按字符分割，可改为按词分割

                    // 创建带进度的文本节点
                    const spannedText = wordArray.map((char, index) =>
                        `<span class="progress-text" data-index="${index}">${char}</span>`
                    ).join('');
                    sentenceElement.innerHTML = spannedText;

                    fetch('/speak', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ text: text })
                    })
                    .then(response => response.json())
                    .then(data => {
                        currentAudio = new Audio('data:audio/mp3;base64,' + data.audio);
                        const progressSpans = Array.from(sentenceElement.querySelectorAll('.progress-text'));
                        const totalWords = progressSpans.length;

                        // 计算每个字的播放时间点（示例：匀速播放，可根据实际音频时长调整）
                        currentAudio.onloadedmetadata = () => {
                            const duration = currentAudio.duration;
                            progressInterval = setInterval(() => {
                                const progress = (currentAudio.currentTime / duration) * totalWords;
                                progressSpans.forEach((span, index) => {
                                    span.style.color = index < progress ? '#2196f3' : '#333';
                                });
                            }, 50); // 50ms更新一次
                        };

                        currentAudio.onended = () => {
                            clearInterval(progressInterval);
                            resetSentenceColor(sentenceElement);
                        };

                        currentAudio.play().catch(error => {
                            if (error.name === 'NotAllowedError') {
                                alert('请先点击页面激活音频播放');
                            }
                        });
                    });
                }

                function resetSentenceColor(element) {
                    element.querySelectorAll('.progress-text').forEach(span => {
                        span.style.color = '#333'; // 重置为默认颜色
                    });
                }

                // 点击事件处理（词汇和句子统一处理）
                function setupAudioControls() {
                    // 页面首次点击处理浏览器自动播放限制
                    let isFirstClick = true;
                    document.body.addEventListener('click', function firstClickHandler() {
                        if (isFirstClick) {
                            const silentAudio = new Audio('data:audio/wav;base64,UklGRl9vT19XQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YU');
                            silentAudio.play().then(() => silentAudio.pause());
                            isFirstClick = false;
                            document.body.removeEventListener('click', firstClickHandler);
                        }
                    });

                    // 词汇行点击
                    document.querySelectorAll('.vocab-row').forEach(row => {
                        row.addEventListener('click', function (e) {
                            if (!e.target.closest('button')) {
                                const pinyin = this.dataset.pinyin;
                                speakText(pinyin, this.querySelector('td:first-child')); // 传递词汇对应的td元素
                            }
                        });
                    });

                    // 发音按钮点击
                    document.querySelectorAll('.speak-btn').forEach(btn => {
                        btn.addEventListener('click', function (e) {
                            e.stopPropagation();
                            const pinyin = this.dataset.pinyin;
                            speakText(pinyin, this.closest('.vocab-row').querySelector('td:first-child'));
                        });
                    });

                    // 课文句子点击
                    document.querySelectorAll('.sentence-container').forEach(container => {
                        container.addEventListener('click', function () {
                            speakText(this.textContent, this);
                        });
                    });
                }

                document.addEventListener('DOMContentLoaded', () => {
                    setupAudioControls();
                });
            </script>

            <!-- 课前准备 -->
            <section id="preparation">
                <div class="page-heading">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-md-12">
                                <br/><br/>
                                <h1 style="color: #535ba0;">课前准备---Preparation</h1>
                            </div>
                        </div>
                    </div>
                </div>
                <br/>
                <!-- 1熟悉这些人物 -->
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="section-heading">
                                <h2 style="color: #535ba0;">熟悉这些词汇</h2>
                            </div>
                            <div class="alternate-table">
                                <table>
                                    <thead>
                                    <tr>
                                        <th>汉语</th>
                                        <th>拼音</th>
                                        <th>英语</th>
                                        <th>发音</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    {% for item in all_vocabularies %}
                                        <tr class="vocab-row" data-pinyin="{{ item.pinyin }}">
                                            <td>{{ item.chinese }}</td>
                                            <td>{{ item.pinyin }}</td>
                                            <td>{{ item.english }}</td>
                                            <td>
                                                <button class="speak-btn btn btn-sm btn-primary"
                                                        data-pinyin="{{ item.pinyin }}">
                                                    <i class="fas fa-volume-up"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    {% endfor %}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

 <!-- 课文内容 -->
            <br/><br/><br/>
            {% for text in texts %}
                <section id="text{{ loop.index }}">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="section-heading">
                                    <h2 style="color: #535ba0;">{{ text.title }}</h2>
                                    <div class="services">
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="service-item first-item">
                                                    <h4>导学{{ loop.index }} Learning Task</h4>
                                                    <p>{{ text.learning_task|safe }}</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <br/><br/>
                                    <div class="text-content">
                                        {% for paragraph in text.content.split('\n') %}
                                            <div class="sentence-container dialogue-block">
                                                {{ paragraph|safe }}
                                            </div>
                                        {% endfor %}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </section>
            {% endfor %}

            <!-- 注释学习 -->
            <section id="annotation">
                <div class="page-heading">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-md-12">
                                <br/><br/>
                                <h1 style="color: #535ba0;">注释学习---Annotation Learning</h1>
                                <div class="services">
                                    <div class="row">
                                        <div class="col-md-12">
                                            {% for annotation in annotations %}
                                                <div class="service-item first-item">
                                                    <div class="icon"></div>
                                                    <h4>{{ annotation.title }}</h4>
                                                    <p>{{ annotation.content|safe }}</p>
                                                </div>
                                            {% endfor %}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
            </section>
            {% if culture_tips %}
                <section id="culture" class="simple-post">
                    <div class="container-fluid">
                        <h1 style="color: #535ba0;">文化交流---Culture Tips</h1>
                        <br/><br/>
                        <div class="row">
                            <div class="col-md-3">
                                <h2>{{ culture_tips.chinese_title }}</h2>
                                <p>{{ culture_tips.chinese_content|safe }}</p>
                                <br><br>
                            </div>
                            <div class="col-md-9">
                                <h2>{{ culture_tips.english_title }}</h2>
                                <p>{{ culture_tips.english_content|safe }}</p>
                            </div>
                        </div>
                    </div>
                </section>
            {% endif %}
        </div>
    </div>

    <!-- Sidebar -->
    <div id="sidebar">
        <div class="inner">
            <!-- Menu -->
            <nav id="menu">
                <ul>
                    <li><a href="#preparation"><em>课前准备</em></a></li>
                    <li>
                        <span class="opener"><em>课文学习</em></span>
                        <ul>
                            <li><a href="#text1"><em>课文 1</em></a></li>
                            <li><a href="#text2"><em>课文 2</em></a></li>
                            <li><a href="#text3"><em>课文 3</em></a></li>
                            <li><a href="#text4"><em>课文 4</em></a></li>
                        </ul>
                    </li>
                    <li><a href="#annotation"><em>注释学习</em></a></li>
                    <li><a href="#culture"><em>文化交流</em></a></li>
                </ul>
            </nav>
        </div>
    </div>

</div>

<!-- Scripts -->
<!-- Bootstrap core JavaScript -->
<script src="{{ url_for('static', filename='vendor/jquery/jquery.min.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
<script src="{{ url_for('static', filename='thirdassets/js/browser.min.js') }}"></script>
<script src="{{ url_for('static', filename='thirdassets/js/breakpoints.min.js') }}"></script>
<script src="{{ url_for('static', filename='thirdassets/js/transition.js') }}"></script>
<script src="{{ url_for('static', filename='thirdassets/js/owl-carousel.js') }}"></script>
<script src="{{ url_for('static', filename='thirdassets/js/custom.js') }}"></script>
<script src="{{ url_for('static', filename='thirdassets/js/main.js') }}"></script>
<script>
    // 添加滚动监听高亮当前章节
    document.addEventListener('DOMContentLoaded', function () {
        const sections = document.querySelectorAll('section');
        const menuLinks = document.querySelectorAll('#menu a');

        window.addEventListener('scroll', function () {
            let current = '';

            sections.forEach(section => {
                const sectionTop = section.offsetTop;
                const sectionHeight = section.clientHeight;
                if (pageYOffset >= (sectionTop - sectionHeight / 3)) {
                    current = section.getAttribute('id');
                }
            });

            menuLinks.forEach(link => {
                link.classList.remove('active');
                if (link.getAttribute('href').includes(current)) {
                    link.classList.add('active');
                    // 自动展开父级菜单
                    const parentLi = link.closest('ul').previousElementSibling;
                    if (parentLi && parentLi.classList.contains('opener')) {
                        parentLi.parentElement.classList.add('active');
                    }
                }
            });
        });
    });
</script>
</body>

</html>